package com.example.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean set(String key, String value){
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e){
            log.error("RedisUtil error set({}, {}) ", key, value, e);
        }
        return false;
    }

    public String get(String key){
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e){
            log.error("RedisUtil error get({}) ", key, e);
        }
        return null;
    }

    public boolean del(String ... key){
        try {
            if(key != null && key.length > 0){
                if(key.length == 1){
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete((Collection<String>)CollectionUtils.arrayToList(key));
                }
            }
            return true;
        } catch (Exception e){
            log.error("RedisUtil error del({}) ", key, e);
        }
        return false;
    }

    public boolean set(String key, String value, Long ttl){
        try {
            redisTemplate.opsForValue().set(key, value, ttl, TimeUnit.SECONDS);
            return true;
        } catch (Exception e){
            log.error("RedisUtil error set({}, {}, {}) ", key, value, ttl, e);
        }
        return false;
    }

    public boolean hasKey(String key){
        try {
            return StringUtils.hasText(key) ? redisTemplate.hasKey(key) : false;
        } catch (Exception e){
            log.error("RedisUtil error hasKey({}) ", key, e);
        }
        return false;
    }
}
